package controller.student;

import com.fasterxml.jackson.databind.ObjectMapper;
import dto.ChooseClassDTO;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import service.impl.StudentServiceImpl;
import util.BaseResult;

import java.io.BufferedReader;
import java.io.IOException;

@WebServlet(urlPatterns = "/chooseClass")
public class ChooseClassServlet extends HttpServlet {
    private static final Logger logger = LoggerFactory.getLogger(StudentServlet.class);
    private static final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            req.setCharacterEncoding("UTF-8");
            resp.setContentType("application/json;charset=UTF-8");
            BufferedReader reader = req.getReader();

            ChooseClassDTO dto = objectMapper.readValue(reader, ChooseClassDTO.class);

            StudentServiceImpl service = new StudentServiceImpl();
            service.chooseClass(dto);

            resp.setContentType("application/json;charset=UTF-8");

            BaseResult<Void> result = BaseResult.success();
            // 序列化并写入响应
            String jsonResponse = objectMapper.writeValueAsString(result);
            resp.getWriter().write(jsonResponse);
        } catch (Exception e) {
            logger.error("添加学生班级错误", e);

            BaseResult<Void> errorResult = BaseResult.failed(500, "添加学生班级失败: " + e.getMessage());

            resp.setContentType("application/json;charset=UTF-8");
            resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);

            String jsonError = objectMapper.writeValueAsString(errorResult);
            resp.getWriter().write(jsonError);
        }
    }
}
